#import <Foundation/NSNotification.h>
#import <Foundation/NSUserDefaults.h>
#import <Foundation/NSBundle.h>	// NSLocalizedString()
#import <UIKit/UIPreferencesTableCell.h>
#import <UIKit/UIPreferencesTextTableCell.h>
#import <UIKit/UIPreferencesControlTableCell.h>
#import <UIKit/UIAlertSheet.h>
#import <UIKit/UISwitchControl.h>
#import <UIKit/UINavigationBar.h>
#import <UIKit/UINavigationItem.h>
#import <UIKit/UITable.h>
#import <UIKit/UITableColumn.h>
#import <UIKit/UISimpleTableCell.h>
#import <UIKit/UITransitionView.h>

#import "PreferencesView.h"

@implementation PreferencesView

- (id)initWithFrame: (CGRect)frame parent: (UIApplication *)app
{
	self = [super initWithFrame: frame];
	
	parent = app;
	
	CGSize navBarSize = [UINavigationBar defaultSize];
	
	// defaults
	NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
	
	// is showing
	showing = false;
	
	// host array
	hosts = [[NSMutableArray arrayWithCapacity: 1] retain];
	{
		int count = [defaults integerForKey: @"host_count"];
		for (int i = 0; i != count; ++i)
			[hosts addObject: [defaults objectForKey: [NSString stringWithFormat: @"host%02d", i]]];
	}
	if ([hosts count] == 0)
		[hosts addObject: [defaults objectForKey: @"current_host"]];
	
	// navigation bar
	navBar = [[UINavigationBar alloc] initWithFrame: CGRectMake(0, 0, frame.size.width, navBarSize.height)];
	[navBar showButtonsWithLeftTitle: nil rightTitle: nil leftBack: YES];
	[navBar setDelegate: self];	// NavigationBar delegate
	[navBar pushNavigationItem: [[UINavigationItem alloc] initWithTitle: NSLocalizedString(@"Back", nil)]];
	
	
	CGRect tableFrame = CGRectMake(0, navBarSize.height, frame.size.width, frame.size.height - navBarSize.height);
	CGRect tableSize = CGRectMake(0, 0, frame.size.width, frame.size.height - navBarSize.height);
	
	// table
	table = [[UIPreferencesTable alloc] initWithFrame: tableSize];
	[table setDelegate: self];
	[table setDataSource: self];
	[table reloadData];
	
	// host list
	hostTable = [[UITable alloc] initWithFrame: tableSize];
	[hostTable setDataSource: self];
	[hostTable setDelegate: self];
	[hostTable addTableColumn: [[[UITableColumn alloc] initWithTitle: @"Host" identifier: @"host" width: frame.size.width] autorelease]];
	[hostTable reloadData];
	
	// transition view
	view = [[UITransitionView alloc] initWithFrame: tableFrame];
	[view transition: 0 toView: table];
	
	// main view
	[self addSubview: navBar];
	[self addSubview: view];
	
	// table row items
	host = [[UIPreferencesTableCell alloc] init];
	[host setTitle: NSLocalizedString(@"Host", nil)];
	[host setValue: [defaults objectForKey: @"current_host"]];
	
	clickSound = [[UISwitchControl alloc] initWithFrame: CGRectMake(200, 10, 50, 20)];
	[clickSound setValue: [defaults boolForKey: @"enable_click_sound"]];
	clickSoundCell = [[UIPreferencesControlTableCell alloc] init];
	[clickSoundCell setTitle: NSLocalizedString(@"Click Sound", nil)];
	[clickSoundCell setControl: clickSound];
	
	mousePanel = [[UISwitchControl alloc] initWithFrame: CGRectMake(200, 10, 50, 20)];
	[mousePanel setValue: [defaults boolForKey: @"enable_mouse_panel"]];
	mousePanelCell = [[UIPreferencesControlTableCell alloc] init];
	[mousePanelCell setTitle: NSLocalizedString(@"Mouse Panel", nil)];
	[mousePanelCell setControl: mousePanel];
	
	inputPanel = [[UISwitchControl alloc] initWithFrame: CGRectMake(200, 10, 50, 20)];
	[inputPanel setValue: [defaults boolForKey: @"enable_input_panel"]];
	inputPanelCell = [[UIPreferencesControlTableCell alloc] init];
	[inputPanelCell setTitle: NSLocalizedString(@"Input Panel", nil)];
	[inputPanelCell setControl: inputPanel];
	
	mouseMoveAbsolute = [[UISwitchControl alloc] initWithFrame: CGRectMake(200, 10, 50, 20)];
	[mouseMoveAbsolute setValue: [defaults boolForKey: @"mouse_move_absolute"]];
	mouseMoveAbsoluteCell = [[UIPreferencesControlTableCell alloc] init];
	[mouseMoveAbsoluteCell setTitle: NSLocalizedString(@"Absolute", nil)];
	[mouseMoveAbsoluteCell setControl: mouseMoveAbsolute];
	
	mouseRotateLandscape = [[UISwitchControl alloc] initWithFrame: CGRectMake(200, 10, 50, 20)];
	[mouseRotateLandscape setValue: [defaults boolForKey: @"mouse_rotate_landscape"]];
	mouseRotateLandscapeCell = [[UIPreferencesControlTableCell alloc] init];
	[mouseRotateLandscapeCell setTitle: NSLocalizedString(@"Rotate Landscape", nil)];
	[mouseRotateLandscapeCell setControl: mouseRotateLandscape];
	
	leftBind = [[UIPreferencesTextTableCell alloc] init];
	[leftBind setTitle: NSLocalizedString(@"Left", nil)];
	[leftBind setValue: [defaults objectForKey: @"status_bar_bind_left"]];
	
	centerBind = [[UIPreferencesTextTableCell alloc] init];
	[centerBind setTitle: NSLocalizedString(@"Center", nil)];
	[centerBind setValue: [defaults objectForKey: @"status_bar_bind_center"]];
	
	rightBind = [[UIPreferencesTextTableCell alloc] init];
	[rightBind setTitle: NSLocalizedString(@"Right", nil)];
	[rightBind setValue: [defaults objectForKey: @"status_bar_bind_right"]];
	
	return self;
}

- (void)dealloc
{
	[navBar release];
	[table release];
}

- (BOOL)isShowing
{
	return showing;
}

- (BOOL)show
{
	if (showing)
		return false;
	
	[navBar pushNavigationItem: [[UINavigationItem alloc] initWithTitle: NSLocalizedString(@"Preferences", nil)]];
	
	return showing = true;
}

- (void)save
{
	NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
	[defaults setInteger: [hosts count] forKey: @"host_count"];
	for (int i = 0; i != [hosts count]; ++i)
		[defaults setObject: [hosts objectAtIndex: i] forKey: [NSString stringWithFormat: @"host%02d", i]];
	[defaults setObject: [host value] forKey: @"current_host"];
	[defaults setBool: [clickSound value] forKey: @"enable_click_sound"];
	[defaults setBool: [mousePanel value] forKey: @"enable_mouse_panel"];
	[defaults setBool: [inputPanel value] forKey: @"enable_input_panel"];
	[defaults setBool: [mouseMoveAbsolute value] forKey: @"mouse_move_absolute"];
	[defaults setBool: [mouseRotateLandscape value] forKey: @"mouse_rotate_landscape"];
	[defaults setObject: [leftBind value] forKey: @"status_bar_bind_left"];
	[defaults setObject: [centerBind value] forKey: @"status_bar_bind_center"];
	[defaults setObject: [rightBind value] forKey: @"status_bar_bind_right"];
	// [defaults synchronize];
}

- (NSString *)host
{
	return [host value];
}

- (BOOL)isClickSoundEnabled
{
	return [clickSound value];
}

- (BOOL)mouseMoveAbsolute
{
	return [mouseMoveAbsolute value];
}

- (BOOL)mouseRotateLandscape
{
	return [mouseRotateLandscape value];
}

- (int)mouseMargin
{
	return [mouseMargin value];
}

- (NSString *)leftBind
{
	return [leftBind value];
}

- (NSString *)centerBind
{
	return [centerBind value];
}

- (NSString *)rightBind
{
	return [rightBind value];
}

- (void)reloadData
{
	[table reloadData];
}

// navigation bar delegates
- (void)navigationBar: (UINavigationBar *)navigationBar poppedItem: (UINavigationItem *)item
{
	if ([[item title] isEqualToString: NSLocalizedString(@"Host List", nil)])	// Preferences <- Host List
	{
		[navBar showButtonsWithLeftTitle: nil rightTitle: nil];	// hide "New" button
		[view transition: 2 toView: table];
		[table reloadData];
	}
	else if ([[item title] isEqualToString: NSLocalizedString(@"Preferences", nil)])	// Hide Preferences
	{
		[self save];
		
		showing = false;
		[parent navigationBar: navBar poppedItem: item];
	}
}

- (void)navigationBar: (UINavigationBar*)navigationBar buttonClicked: (int)button
{
	switch (button)
	{
		// right button
		// New
		case 0:
		{
			NSArray *buttons = [NSArray arrayWithObjects: @"Add", @"Cancel", nil];
			UIAlertSheet *sheet = [[UIAlertSheet alloc] initWithTitle: @"New Host" buttons: buttons defaultButtonIndex: 2 delegate: self context: self];
			[sheet addTextFieldWithValue: @"192.168.0.16:7378" label: @"IP_ADDRESS:Port"];
			[[sheet textField] setPreferredKeyboardType: 3];	// http://www.cocoadev.com/index.pl?UIKeyboard
			[sheet popupAlertAnimated: YES];
			break;
		}
	}
}

- (void)alertSheet: (UIAlertSheet *)sheet buttonClicked: (int)button
{
	[sheet dismiss];
	
	switch (button)
	{
		case 1:	// Add, should use enum
		{
			NSString *text = [[sheet textField] text];
			if (![hosts containsObject: text])
				[hosts addObject: text];
			break;
		}
		
		case 2:	// Cancel
			break;
	}
	
	[hostTable reloadData];
}

/*
	HostTable
*/
- (int)numberOfRowsInTable: (UITable*)table
{
	return [hosts count];
}

- (UITableCell*)table: (UITable*)table cellForRow: (int)row column: (UITableColumn *)column
{
	UISimpleTableCell *cell = [[UISimpleTableCell alloc] init];
	if (table == hostTable && 0 <= row && row < [hosts count])
		[cell setTitle: [hosts objectAtIndex: row]];
	
	return [cell autorelease];
}

/*
	swipe to delete
	http://idevdocs.com/forum/showthread.php?t=78&highlight=UITable
*/
- (void)table: (UITable *)table willSwipeToDeleteRow: (int)row
{
	if (table == hostTable && 0 <= row && row < [hosts count])
		[hostTable setDeleteConfirmationRow: row];
}


- (BOOL)table: (UITable *)table canDeleteRow: (int)row
{
	if (table == hostTable && 0 <= row && row < [hosts count])
		return YES;
	
	return NO;
}

- (void)table: (UITable *)table deleteRow: (int)row 
{
	if (table == hostTable)
		[hosts removeObjectAtIndex: row];
}

// delegates
- (void)tableRowSelected: (NSNotification *)notification
{
	id sender = [notification object];
	
	if (sender == table)
	{
		int row = [sender selectedRow];
		if (row != 1)	return;
		
		[navBar pushNavigationItem: [[[UINavigationItem alloc] initWithTitle: NSLocalizedString(@"Host List", nil)] autorelease]];
		[navBar showButtonsWithLeftTitle: nil rightTitle: NSLocalizedString(@"New", nil)];
		
		[view transition: 1 toView: hostTable];
	}
	else if (sender == hostTable)
	{
		int row = [sender selectedRow];
		// host selected
		[navBar showButtonsWithLeftTitle: nil rightTitle: nil];
		[navBar popNavigationItem];
		if (0 <= row && row < [hosts count])
			[host setValue: [hosts objectAtIndex: row]];
	}
}

// data sources
- (int)numberOfGroupsInPreferencesTable: (UIPreferencesTable *)table
{
	return 4;
}

- (int)preferencesTable: (UIPreferencesTable *)table numberOfRowsInGroup: (int)group
{
	switch (group)
	{
		case 0:	// Host
			return 1;
		case 1:	// Panel
			return 3;
		case 2:	// Mouse
			return 2;
		case 3:	// Status Bar
			return 3;
	}
	return 0;
}

- (NSString *)preferencesTable: (UIPreferencesTable *)table titleForGroup: (int)group
{
	switch (group)
	{
		case 0:
			return NSLocalizedString(@"Host", nil);
		case 1:
			return NSLocalizedString(@"Panel", nil);
		case 2:
			return NSLocalizedString(@"Mouse", nil);
		case 3:
			return NSLocalizedString(@"Status Bar", nil);
	}
	
	return nil;
}

- (UIPreferencesTableCell *)preferencesTable: (UIPreferencesTable *)table cellForRow: (int)row inGroup: (int)group
{
	NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
	
	switch (group)
	{
		case 0:	// Host
			switch (row)
			{
				case 0:
					return host;
			}
		
		case 1:	// Panel
			switch (row)
			{
				case 0:
					return clickSoundCell;
				case 1:
					return mousePanelCell;
				case 2:
					return inputPanelCell;
			}
		
		case 2:	// Mouse
			switch (row)
			{
				case 0:
					return mouseMoveAbsoluteCell;
				case 1:
					return mouseRotateLandscapeCell;
			}
		
		case 3:	// Status Bar
			switch (row)
			{
				case 0:
					return leftBind;
				case 1:
					return centerBind;
				case 2:
					return rightBind;
			}
	}
	
	return nil;
}

@end
